<template>
  <div class="action">
    <!-- 操作 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="考场名称：" v-if="mohukai">
        <el-input
          v-model="formInline.search"
          placeholder="--请输入考场名称--"
          clearable
        />
      </el-form-item>
      <el-form-item v-if="kaiguan && !quanx" label="学生姓名：">
        <el-input
          v-model="formInline.search1"
          placeholder="--请输入学生姓名--"
          clearable
        />
      </el-form-item>
      <el-form-item v-if="kaiguan && !quanx" label="班级">
        <el-select-v2
          v-model="formInline.leibie2"
          :options="banjie"
          placeholder="--请选择班级--"
          clearable
          style="margin-top: 10px"
        />
      </el-form-item>
      <el-form-item v-if="kaiguan && quanx" label="类别">
        <el-select-v2
          v-model="formInline.leibie"
          :options="initials"
          placeholder="--请选择类别--"
          clearable
          style="margin-top: 10px"
        />
      </el-form-item>
      <el-button type="primary" @click="monikao" v-if="quanx" plain
        >模拟考</el-button
      >
    </el-form>

   
    <!-- 卡片 -->
    <el-tabs v-model="activeName" type="border-card" @click="kapikao">
      <el-tab-pane label="考试记录" name="kaoshijilu" height="600">
        <!-- 表单1 -->
        <el-table :data="gettableData" style="width: 100%">
          <el-table-column
            fixed
            prop="start_exam_time"
            label="考试时间"
            width="170"
            sortable
          >
            <template #default="{ row }">
              {{ formattedCreateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="examination_id"
            label="编号"
            sortable
            width="120"
          />
          <el-table-column prop="class_name" label="班级" sortable />
          <el-table-column prop="nick_name" label="参考人员" />
          <el-table-column prop="exam_name" label="考场" />
          <el-table-column prop="examination_score" label="试卷总分" />
          <el-table-column prop="direction_name" label="试卷类型" />
          <el-table-column prop="scor" label="试卷得分" sortable />
          <el-table-column prop="duration" label="考试用时" sortable />
          <!-- <el-table-column fixed="right" label="操作" min-width="120">
            <template #default>
              <el-button link type="primary" size="small">查看</el-button>
            </template>
          </el-table-column> -->
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="模拟记录" v-if="quanx" name="second">
        <!-- 表单2 -->
        <el-table :data="gettableData2" style="width: 100%">
          <el-table-column
            fixed
            prop="simulated_exam_time"
            label="考试时间"
            width="150"
            sortable
          >
            <template #default="{ row }">
              {{ formattedCreateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="simulated_exam_id"
            label="模拟考编号"
            sortable
          />
          <el-table-column prop="score" label="模拟考得分" sortable />
          <el-table-column prop="time_used" label="模拟考用时" sortable>
            <template #default="{ row }">
              {{ formatTime01(row.time_used) }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" min-width="120">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="handleClick(scope.row)"
              >
                删除
              </el-button>
              <!-- <el-button link type="primary" size="small">重考</el-button> -->
              <el-button
                link
                type="primary"
                size="small"
                @click="SelectionErrorMessage(scope.row.error_message)"
                v-if="!scope.row.error_message"
              >
                查看错误详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="错题记录" v-if="quanx" name="third">
        <el-table :data="errorSubject" style="width: 100%">
          <el-table-column
            prop="subject_id"
            label="错题编号"
            width="100"
          ></el-table-column>
          <el-table-column
            prop="subject_name"
            label="题目信息"
            width="300"
          ></el-table-column>
          <el-table-column
            prop="subject_type"
            label="题目类型"
            width="100"
            :formatter="formatSubjectType"
          >
          </el-table-column>
          <el-table-column
            prop="label_name"
            label="题目类别"
            width="110"
          ></el-table-column>
          <el-table-column
            prop="ordinalNumber"
            label="错误次数"
            width="150"
            sortable
          ></el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
      <!-- 弹窗 -->
    <el-dialog
      v-model="centerDialogVisible"
      title="模拟考试"
      width="500"
      align-center
    >
      <el-form>
        <el-form-item label="请选择类别">
          <el-select-v2
            v-model="formInline.leibie2"
            :options="initials"
            placeholder="--请选择--"
            clearable
            style="padding: 19px;"
          />
        </el-form-item>
        <el-form-item label="请选择难度">
          <el-select-v2
            v-model="formInline.difficulty"
            :options="difficultyOptions"
            placeholder="请选择难度"
            clearable
            style="padding: 19px;"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="monikao">取消</el-button>
          <el-button type="primary" @click="monikaotiao"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
     <!-- 错误信息对话框 -->
    <el-dialog title="错误信息" v-model="showErrorMessageDialog" width="50%">
      <div v-html="errorMessageDetails"></div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showErrorMessageDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
  
<script  setup>
import { ElMessage } from "element-plus";
import {
  findClassroomByClassId,
  findClassroomByTeacherId,
  deleteExamResults,
  banjiget,
  getErrorSubjcet,
} from "@/api/kaoshi/index2.js";
import { computed, onMounted, ref } from "vue";
import dayjs from "dayjs";
import { useUserInfoStore } from "@/store/user.js";
const userInfoStore = useUserInfoStore();
const difficultyOptions = ref([
  { value: 1, label: "简单" },
  { value: 2, label: "中等" },
  { value: 3, label: "困难" },
]);

const errorMessageDetails = ref("");
const showErrorMessageDialog = ref(false);
// 格式化题目类型
const formatSubjectType = (row) => {
  switch (row.subject_type) {
    case 0:
      return "判断";
    case 1:
      return "多选";
    case 2:
      return "单选";
    default:
      return "未知";
  }
};
const SelectionErrorMessage = (errorMessage) => {
  if (errorMessage !== undefined && errorMessage !== null) {
    // 将错误信息转换为 HTML 格式
    const formattedMessage = errorMessage.replace(/<br>/g, "<br>");
    errorMessageDetails.value = formattedMessage;
    showErrorMessageDialog.value = true;
  } else {
    ElMessage.error("错误信息不存在");
  }
};
//权限限制管理
const quanx = ref(true);
const xianshi = () => {
  if (userInfoStore.userInfo.userType == 1) {
    quanx.value = false;
  } else {
    quanx.value = true;
  }
};
// 方法，将秒数转换为 HH:mm:ss 格式
const formatTime = (timeInSeconds) => {
  // 输入验证，确保 timeInSeconds 是一个有效的数字
  if (typeof timeInSeconds !== "number" || isNaN(timeInSeconds)) {
    console.error("Invalid input: timeInSeconds must be a valid number");
    return "00:00:00"; // 返回默认值或根据需求调整
  }

  try {
    // 使用 dayjs 格式化时间
    return dayjs.duration(timeInSeconds, "seconds").format("HH:mm:ss");
  } catch (error) {
    console.error("Error formatting time:", error);
    return "00:00:00"; // 返回默认值或根据需求调整
  }
};
const formatTime01 = (timeInSeconds) => {
  let minutes = Math.floor((timeInSeconds % 3600) / 60);
  const seconds = Math.floor(timeInSeconds % 60);
  return `${String(minutes).padStart(2, "0")}分-${String(seconds).padStart(
    2,
    "0"
  )}秒`;
};
//卡片
const kaiguan = ref(true);
const activeName = ref("kaoshijilu");
const mohukai = ref(true);
const kapikao = () => {
  if (activeName.value == "kaoshijilu") {
    mohukai.value = true;
    kaiguan.value = true;
  } else if (activeName.value == "second") {
    kaiguan.value = false;
    mohukai.value = true;
  } else {
    kaiguan.value = false;
    mohukai.value = false;
  }
};
//路由
import router from "@/router";
//弹窗控制
const centerDialogVisible = ref(false);
const monikao = () => {
  formInline.value.fregion = "";
  if (centerDialogVisible.value == true) {
    centerDialogVisible.value = false;
  } else {
    centerDialogVisible.value = true;
  }
};
//序列化时间
const formattedCreateTime = (createTime) => {
  return dayjs(createTime).format("YYYY-MM-DD");
};
//弹窗操作确认
const monikaotiao = () => {
  monikao();
  router.push({
    path: "/exam/analog",
    query: {
      subjectMajor: formInline.value.leibie2,
      subjectLv: formInline.value.difficulty,
    },
  });
};

// 点击删除
const handleClick = async (row) => {
  let data = await deleteExamResults(row.simulated_exam_id);
  if (data.data) {
    settableData();
    settableData2();
    ElMessage({
      message: "清除成功",
      type: "success",
    });
  } else {
    ElMessage.error("清除失败");
  }
};
// 去查询的数据
const formInline = ref({
  search: "",
  search1: "",
  leibie: "",
  leibie2: "",
});
//表格1数据
const tableData = ref([]);
const tableData2 = ref([]);
//获取考试历史数据
const settableData = async () => {
  let qingqiu = ref({
    userid: userInfoStore.userInfo.userId || 0,
    usertype: userInfoStore.userInfo.userType || 0,
    direction: userInfoStore.userInfo.majorId || 0,
  });
  let res = await findClassroomByClassId(qingqiu.value);
  if (res.code === 200) {
    tableData.value = res.data;
    // console.log(res.data);
  }
};
//获取模拟考记录
const settableData2 = async () => {
  let params = {
    uid: userInfoStore.userInfo.userId || 0,
  };
  let data = await findClassroomByTeacherId(params.uid);
  // console.log(data);
  if (data.code === 200) {
    tableData2.value = data.data;
  }
};
// 定义一个计算属性 filterTableData
const gettableData = computed(() => {
  return tableData.value.filter((data) => {
    let search = String(formInline.value.search).toLowerCase() || "";
    let search1 = String(formInline.value.search1).toLowerCase() || "";
    let leibie =
      formInline.value.leibie !== null && formInline.value.leibie !== undefined
        ? String(formInline.value.leibie).toLowerCase()
        : "";
    let leibie2 =
      formInline.value.leibie2 !== null &&
      formInline.value.leibie2 !== undefined
        ? String(formInline.value.leibie2).toLowerCase()
        : "";

    let name = String(data.exam_name).toLowerCase() || "";
    let name1 = String(data.nick_name).toLowerCase() || "";
    let dataLeibie = String(data.direction_id).toLowerCase() || "";
    let dataLeibie2 = String(data.class_id).toLowerCase() || "";
    // console.log(data);
    return (
      (!search || name.includes(search)) &&
      (!leibie || dataLeibie.includes(leibie)) &&
      (!search1 || name1.includes(search1)) &&
      (!leibie2 || dataLeibie2.includes(leibie2))
    );
  });
});
const gettableData2 = computed(() => {
  return tableData2.value.filter((data) => {
    let search = String(formInline.value.search).toLowerCase() || "";

    let name = String(data.simulated_exam_id).toLowerCase() || "";

    return !search || name.includes(search);
  });
});
const errorSubject = ref([]);
//查询专业课程
import { direction } from "@/api/common/work/courseManager.js";
const initials = ref([]);
// 查询专业方向
const directionss = async () => {
  try {
    let res = await direction();
    if (res.data) {
      initials.value.push(
        ...res.data.map((item) => ({
          value: item.directionId,
          label: item.directionName,
        }))
      );
    } else {
      console.error("res.data is null or undefined");
    }
  } catch (error) {
    console.error("Error fetching direction:", error);
  }
};
//查询班级信息
const banjie = ref([]);
const banjiset = async () => {
  try {
    let res = await banjiget(userInfoStore.userInfo.userId);
    // console.log(res.data);
    if (res.data) {
      banjie.value.push(
        ...res.data.map((item) => ({
          value: item.classId,
          label: item.className,
        }))
      );
    } else {
      console.error("res.data is null or undefined");
    }
  } catch (error) {
    console.error("Error fetching direction:", error);
  }
};

// 假设 getErrorSubjcet 是一个返回 Promise 的函数
async function fetchErrorSubject(userId) {
  try {
    const ref = await getErrorSubjcet(userId);
    // console.log(ref);  // 这里输出获取的结果
    errorSubject.value = ref.data;
  } catch (error) {
    console.error("获取错误信息失败:", error);
  }
}

// 获取用户信息并传递给方法

//加载
const shuju = () => {
  banjiset();
  xianshi();
  directionss();
  settableData();
  settableData2();
  fetchErrorSubject(userInfoStore.userInfo.userId);
};
// 事件
onMounted(() => {
  shuju();
});
</script>


<style lang='scss' scoped>
.action {
  width: 100%;
  height: 100%;
  padding: 10px;
  margin: 10px;
  .demo-form-inline {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    .el-select {
      --el-select-width: 220px;
    }
    .el-input {
      --el-input-width: 220px;
    }
    .el-switch {
      margin-left: 30px;
      width: 200px;
    }
    .el-button {
      margin-top: -10px;
    }
  }
}
</style>